import { reactive, ref } from "vue";
import { useCool } from "/@/cool";
import { useUi } from "/$/cool-ui";
import { onShow } from "@dcloudio/uni-app";
import {getVersion, isAndroid, storage } from "../utils";
import { config } from "/@/config";
import { defineStore } from "pinia";

// 缓存
export const useCache = defineStore("cache", () => {
	// 缓存大小
	const size = ref("0KB");

	// 获取缓存
	function get() {
		// #ifdef APP
		plus.cache.calculate(function (s: number) {
			//size是多少个字节单位是b
			if (s < 1024) {
				size.value = s + "B";
			} else if (s / 1024 >= 1 && s / 1024 / 1024 < 1) {
				size.value = Math.floor((s / 1024) * 100) / 100 + "KB";
			} else if (s / 1024 / 1024 >= 1) {
				size.value = Math.floor((s / 1024 / 1024) * 100) / 100 + "M";
			}
		});
		// #endif
	}

	// 清空缓存
	function clear() {
		// #ifdef APP
		plus.cache.clear(function () {
			get();
		});
		// #endif
	}

	onShow(() => {
		get();
	});

	return {
		size,
		get,
		clear,
	};
});

// 消息通知
export const useNotice = defineStore("notice", () => {
	// 是否开启
	const enabled = ref(false);

	// 获取状态
	function get() {
		// #ifdef APP
		const UIApplication = plus.ios.import("UIApplication");
		const app = UIApplication.sharedApplication();
		if (app.currentUserNotificationSettings) {
			const settings = app.currentUserNotificationSettings();
			enabled.value = settings.plusGetAttribute("types") != 0;
			plus.ios.deleteObject(settings);
		} else {
			enabled.value = app.enabledRemoteNotificationTypes() != 0;
		}

		plus.ios.deleteObject(app);
		// #endif
	}

	// 打开设置
	function open() {
		// #ifdef APP
		const UIApplication = plus.ios.import("UIApplication");
		const app = UIApplication.sharedApplication();
		const NSURL2 = plus.ios.import("NSURL");
		const settings = NSURL2.URLWithString("app-settings:");
		app.openURL(settings);
		// #endif
	}

	onShow(() => {
		// get();
	});

	return {
		enabled,
		get,
		open,
	};
});

// 版本信息
export const useVersion = defineStore("version", () => {
	// 版本号
	const num = ref("");

	// 是否能升级
	const isUpgrade = ref(false);

	// 检测状态
	const loading = ref(false);

	// 新版本信息
	const updateInfo = ref<Eps.app>();

	// 获取版本号
	function get() {
		return getVersion().then((version : any) => {
			num.value = version;
		});
	}
	get();
	// 检测更新
	async function check() {
		loading.value = true;
		await get()
		let brand = uni.getSystemInfoSync().brand
		return await useCool().service.app.version
			.check({
				version: num.value,
				type: isAndroid ? 0 : 1,
				brand: brand?.toLowerCase()
			})
			.then((res : { version : string; }) => {
				if (res) {
					console.log("[version] 新版本信息", res);
					updateInfo.value = res;
					isUpgrade.value = compareVersions(res?.version, num.value) === 1;
					if (res.version > num.value) {
						num.value = res.version;
					} 
				}
				loading.value = false;
				return res
			})
			.catch((err : { message : any; }) => {
				loading.value = false;
				useUi().showToast(err.message);
			});

	}
	// 更新资源包
	function update(isConfirm : boolean = true) {
		const { url, forceUpdate, version, description, hotUpdate } = updateInfo.value || {};

		function next() {
			if (!isUpgrade.value) {
				return false;
			}

			if (!updateInfo.value) {
				return useUi().showToast("未检测到版本信息");
			}

			if (!url) {
				return useUi().showToast(hotUpdate ? "资源包错误" : "APP下载地址错误");
			}

			if (hotUpdate) {
				useUi().showLoading("下载资源包");

				uni.downloadFile({
					url: url,
					success(res) {
						console.log(res)
						useUi().hideLoading();
						if (res.statusCode == 200) {
							plus.runtime.install(
								res.tempFilePath,
								{ force: true },
								() => {
									num.value = version;
									useUi().showToast("更新成功，重启中");
									setTimeout(()=>{
										plus.runtime.restart();
									},1000)
								},
							);
						} else {
							useUi().showToast("下载资源包失败");
						}
					},
					complete(res) {
						console.log(res)
						useUi().hideLoading();
					},
				});
			} else {
				plus.runtime.openURL(url);
			}
		}

		if (isUpgrade.value) {
			if (isConfirm) {
				useUi().showConfirm({
					title: "检查到新版本",
					message: description,
					confirmButtonText: "立即更新",
					callback(action) {
						if (action == "confirm") {
							next();
						}
					},
				});
			} else {
				next();
			}
		} else {
			useUi().showToast("当前已是最新版本");
		}
	}


	return {
		num,
		isUpgrade,
		loading,
		get,
		check,
		update
	};
});
// 版本比较
function compareVersions(v1 : string, v2 : string) {
	const arr1 = v1.split(".").map(Number);
	const arr2 = v2.split(".").map(Number);
	const maxLength = Math.max(arr1.length, arr2.length);

	for (let i = 0; i < maxLength; i++) {
		const num1 = arr1[i] || 0;
		const num2 = arr2[i] || 0;

		if (num1 > num2) return 1;
		if (num2 > num1) return -1;
	}

	return 0;
}
// 主题
export const useTheme = defineStore("theme", () => {
	const name = ref(storage.get("theme") || "default");

	function set(value: string) {
		name.value = value;
		storage.set("theme", "default");
	}

	return {
		name,
		set,
	};
});

export function useApp() {
	const info = reactive(config.app);

	return {
		info,
		theme: useTheme(),
		cache: useCache(),
		notice: useNotice(),
	};
}
